package com.odianyun.springcloud.internship.oms.startup.config;

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validator;

/**
 * @description:
 * @author: EDZ
 * @time: 14:46
 * @date: 2021/7/26
 */
@Configuration
public class MessageConfig {

    @Bean
    public MessageSource localeMessageSource() {
        ResourceBundleMessageSource messageSource = buildMessageSource();
        messageSource.setBasenames("message/locale", "message/i18n");
        return messageSource;
    }

    @Bean
    public MessageSource validatorMessageSource() {
        ResourceBundleMessageSource messageSource = buildMessageSource();
        messageSource.setBasenames("message/ValidationMessages");
        return messageSource;
    }

    @Bean
    public Validator validator(MessageSource validatorMessageSource) {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        factoryBean.setProviderClass(HibernateValidator.class);
        factoryBean.setValidationMessageSource(validatorMessageSource);
        return factoryBean;
    }

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor(Validator validator) {
        MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
        processor.setValidator(validator);
        return processor;
    }

    private static ResourceBundleMessageSource buildMessageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setUseCodeAsDefaultMessage(false);
        messageSource.setDefaultEncoding("UTF-8");
        return messageSource;
    }
}
